<?php

class ApiController extends Controller
{
   private function _sendResponse($status = 200, $body = '', $content_type = 'text/html')
   {
      $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
      header($status_header);
      header('Content-type: ' . $content_type);
      $message = '';
      if($body != '')
      {
         // send the body
         echo $body;
      }
      // we need to create the body if none is passed
      else
      {
         switch ($status) {
            case 401:
               $message = 'You must be authorized to view this page.';
            break;
            case 404:
               $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
            break;
            case 500:
               $message = 'The server encountered an error processing your request.';
            break;
            case 501:
               $message = 'The requested method is not implemented.';
            break;
         }
         $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
         $status_message = $this->_getStatusCodeMessage($status);
         $this->render('view', array(
            'status' => $status,
            'status_message' => $status_message,
            'message' => $message,
            'signature' => $signature
         ));
         echo $body;
      }
      Yii::app()->end();
   }   
   private function _getStatusCodeMessage($status)
   {
      $codes = Array(
         200 => 'OK',
         400 => 'Bad Request',
         401 => 'Unauthorized',
         402 => 'Payment Required',
         403 => 'Forbidden',
         404 => 'Not Found',
         500 => 'Internal Server Error',
         501 => 'Not Implemented',
      );
      return (isset($codes[$status])) ? $codes[$status] : '';
   }
   
	public function actionIndex()
	{
		//$this->render('index');
	}
   
   public function actionView()
   {
      $this->layout = 'json';
      if (!isset($_GET['id']))
         $this->_sendResponse(500, 'Error: Parameter <b>id</b> is missing' );
      switch($_GET['model'])
      {
         case 'user':
            $model = array('user' => 'cosa');
         break;
         default:
            $this->_sendResponse(501, sprintf(
               'Mode <b>view</b> is not implemented for model <b>%s</b>',
                $_GET['model']) );
            Yii::app()->end();
      }
      if (is_null($model))
        $this->_sendResponse(404, 'No Item found with id '.$_GET['id']);
      else
        $this->_sendResponse(200, CJSON::encode($model));
   }
	public function actionCreate()
	{
		$this->layout = 'json';
		switch ($_GET['model']) {
			case 'projects':
            $model = new Proyecto;                    
            break;
			default:
            $this->_sendResponse(501, 
               sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
               $_GET['model']) );
            Yii::app()->end();
				break;
		}
		$json = file_get_contents('php://input');
		$json = CJSON::decode($json,true);
		//$json = $json[0];
		$model->nombre     			= $json['nombre'];
		$model->antecesor  			= $json['antecesor'];
		$model->inicio_programado  = $json['inicio_programado'];
		$model->fin_programado     = $json['fin_programado'];
		$model->estado             = 'no iniciado';
		$model->actividad          = $json['actividad'];
      if ($model->save())
			$this->_sendResponse(200, CJSON::encode($model));
		else {
			// Errors occurred
			$msg = "<h1>Error</h1>";
			$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
			$msg .= "<ul>";
			foreach($model->errors as $attribute=>$attr_errors) {
            $msg .= "<li>Attribute: $attribute</li>";
            $msg .= "<ul>";
            foreach($attr_errors as $attr_error)
                $msg .= "<li>$attr_error</li>";
            $msg .= "</ul>";
			}
			$msg .= "</ul>";
			$this->_sendResponse(500, $msg );
		}
	}
	public function actionList()
	{	
		switch($_GET['model'])
			{
			case 'parents':
				$models = Proyecto::model()->findAll('actividad != 1');
				break;
			case 'projects':
				$models = Proyecto::model()->findAll();
				break;
			default:
				$this->_sendResponse(501, sprintf(
					'Error: Mode <b>list</b> is not implemented for model <b>%s</b>',
					$_GET['model']) );
				Yii::app()->end();
				break;
			}
			if (empty($models)) {
			  $this->_sendResponse(200, 
						 sprintf('No items where found for model <b>%s</b>', $_GET['model']) );
			}
			else {
				$rows = array();
				foreach($models as $model)
					$rows[] = $model->attributes;
				$this->_sendResponse(200, CJSON::encode($rows));
			}
	}
}